package com.win.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @Author:
 * @Date: 2024/7/19 12:53
 * @Description:
 */
public class CookieDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 请求字符编码
        req.setCharacterEncoding("utf-8");
        // 响应字符编码
        resp.setCharacterEncoding("utf-8");

        //服务器端获取客户端cookie
        Cookie[] cookies = req.getCookies();
        PrintWriter out = resp.getWriter();
        if (cookies!=null) {
            out.write("你上次访问的时间是：");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                //获取cookie的name
                if (cookie.getName().equals("lastLongTime")){
                    //获取cookie的value
                    long l = Long.parseLong(cookie.getValue());
                    Date date = new Date(l);
                    out.write(date.toString());
                }
            }
        }else {
            out.write("lastLongTime");
        }
        //创建cookie
        Cookie cookie = new Cookie("lastLongTime", System.currentTimeMillis() + "");
        //设置cookie的生命周期（有效期）为一天,设置有效期后会变得不安全，浏览器关闭再次访问依然还在
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    }
}
